package stock

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"learning/gooop/saga/mqs/logger"
	"learning/gooop/saga/mqs/models"
	"learning/gooop/saga/order"
	"net/http"
)

func NotifySaleOrderCreated(c *gin.Context) {
	body := c.Request.Body
	defer body.Close()

	j, e := ioutil.ReadAll(body)
	if e != nil {
		logger.Logf("stock.NotifySaleOrderCreated, failed ioutil.ReadAll")
		c.JSON(http.StatusBadRequest, gin.H { "ok": false, "error": e.Error()})
		return
	}

	msg := &models.TxMsg{}
	e = json.Unmarshal(j, msg)
	if e != nil {
		logger.Logf("stock.NotifySaleOrderCreated, failed json.Unmarshal msg")
		c.JSON(http.StatusBadRequest, gin.H { "ok": false, "error": e.Error()})
		return
	}

	order := &order.SaleOrder{}
	e = json.Unmarshal([]byte(msg.Content), order)
	if e != nil {
		logger.Logf("stock.NotifySaleOrderCreated, failed json.Unmarshal order")
		c.JSON(http.StatusBadRequest, gin.H { "ok": false, "error": e.Error()})
		return
	}
	logger.Logf("stock.NotifySaleOrderCreated, order=%s/%v", order.OrderID, order)

	// notify stock service
	_ = MockStockService.HandleSaleOrderCreated(order)
	c.JSON(http.StatusOK, gin.H{ "ok": true })
}


var PathOfNotifySaleOrderCreated = "/notify/sale-order.created"